import numpy as np
from collections import Counter
class KNN:
    def __init__(self, k=3):
        self.k = k
    def fit(self, X, y):
        self.X_train = X
        self.y_train = y
    def predict(self, X):
        return np.array([self._predict_one(x) for x in X])
    def _predict_one(self, x):
        # 计算该样本与所有训练样本的欧式距离
        distances = np.linalg.norm(self.X_train - x, axis=1)
        # 找到距离最近的 k 个样本的索引
        k_idx = np.argsort(distances)[:self.k]
        # 取出对应的标签
        k_neighbor_labels = self.y_train[k_idx]
        # 进行多数投票
        label = Counter(k_neighbor_labels).most_common(1)[0][0]
        return label
        if __name__ == "__main__":
    # 构造两类数据（简单二维）
    X_train = np.array([
        [1, 2], [2, 3], [3, 1],     # 类 0
        [6, 7], [7, 8], [8, 6]      # 类 1
    ])
    y_train = np.array([0, 0, 0, 1, 1, 1])
    knn = KNN(k=3)
    knn.fit(X_train, y_train)
    X_test = np.array([
        [2, 2],
        [7, 7]
    ])

    preds = knn.predict(X_test)
    print("预测结果：", preds)